import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:talk/api/AlarmApi.dart';
import 'package:talk/pages/device/model/DeviceAlarm.dart';
import 'package:talk/pages/device/x_device_router.dart';

import '../../api/DeviceApi.dart';
import '../../commponets/CustomSwitch.dart';
import '../../commponets/ItemView.dart';
import '../../home/AppLocale.dart';
import '../../routers/fluro_navigator.dart';
import '../../tools/widgets/my_app_bar.dart';
import '../provider/CustomBottomPicker.dart';
import 'model/Device.dart';

class DeviceAlarmDefensePage extends StatefulWidget {
  const DeviceAlarmDefensePage({
    super.key,
    this.deviceId,
    this.deviceAlarm,
  });

  final int? deviceId;
  final DeviceAlarm? deviceAlarm;

  @override
  State<DeviceAlarmDefensePage> createState() => _DeviceAlarmDefensePageState();
}

class _DeviceAlarmDefensePageState extends State<DeviceAlarmDefensePage> {
  final DeviceApi _deviceApi = DeviceApi();
  final AlarmApi _alarmApi = AlarmApi();
  late int _deviceId;
  late int _camId;
  DeviceAlarm? _deviceAlarm;

  // 移动侦测开关状态
  late int interComMotionDetection;
  // 移动侦测设置开关状态
  late int interComMotionDetectionSetting;
  // 报警录制开关状态
  late int interAlarmRecord;
  // 防区设置开关状态
  late int interDefenseSetting;

  // 防区设置数据
  List<dynamic> _defenseSettingList = [];


  @override
  void initState() {
    super.initState();
    _deviceId = widget.deviceId!;
    _deviceAlarm = widget.deviceAlarm!;
    _camId = widget.deviceAlarm!.camId!;

    interComMotionDetection = _deviceAlarm?.motionDetection ?? 0;
    interComMotionDetectionSetting = _deviceAlarm?.motionDetectionSetting ?? 0;
    interAlarmRecord = _deviceAlarm?.alarmRecord ?? 0;
    interDefenseSetting = _deviceAlarm?.defenseSetting ?? 0;

    _fetchDefenseSettingData();
  }



  // 获取防区设置数据
  void _fetchDefenseSettingData() async {
      final getInfoFrom = {
        "camId": _camId,
        "weekIlk": 1,
      };
      try {
        final response = await _alarmApi.getAlarmInfo(getInfoFrom);
        if (response.code == 200) {
          setState(() {
            _defenseSettingList = response.data;
          });
        } else {
          debugPrint("获取防区设置数据失败，code: ${response.getMsg}");
        }
      } catch (e) {
        debugPrint("获取防区设置数据异常");
      }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: AppLocale.text('d_fangqushezhi'),
        backgroundColor: Colors.transparent,
        dropdownWidth: 140,
        dropdownBackgroundColor: Colors.white,
        dropdownBorderRadius: 20,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.symmetric(vertical: 20),
        child: Column(
          children: [
            // 防区设置表格
              Container(
                width: 400,
                margin: const EdgeInsets.symmetric(vertical: 1, horizontal: 20),
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8), // 增加圆角半径
                ), // 移除了boxShadow
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: EdgeInsets.only(left: 10, bottom: 10),
                      child: Text(
                        AppLocale.text('d_fangqushezhi'),
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    ListView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: _defenseSettingList.length,
                      itemBuilder: (context, index) {
                        var item = _defenseSettingList[index];
                        return GestureDetector(
                          onTap: () => _onDefenseItemTap(item),
                          child: Container(
                            margin: const EdgeInsets.symmetric(vertical: 5),
                            padding: const EdgeInsets.all(10),
                            decoration: const BoxDecoration(
                              color: Colors.white, // 移除了灰色背景
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      "${item['startTime']} - ${item['endTime']}",
                                      style: const TextStyle(
                                        fontSize: 15.0,
                                        color: Colors.grey,
                                      ),
                                    ),
                                    Text(
                                      _formatWeekText(item['week'] ?? ''), // 调用工具方法
                                      style: const TextStyle(
                                        fontSize: 12.0,
                                        color: Colors.grey,
                                      ),
                                    ),
                                  ],
                                ),
                                CustomSwitch(
                                  value: item['weekStatus'] ?? 0,
                                  size: 25.0,
                                  onChanged: (newValue){
                                    setState(() {
                                      _defenseSettingList[index]['weekStatus'] = newValue;
                                    });

                                    _onDefenseSwitchChanged(item['weekId'], newValue);
                                  },
                                  activeBackgroundColor: Colors.green,
                                  inactiveBackgroundColor: Colors.grey[300]!,
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  ],
                ),
              ),
            const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }


  // 防区设置项点击事件处理
  // void _onDefenseItemTap(dynamic item) {
  //   final encodedweek = Uri.encodeComponent(item['week']);
  //   final encodedstartTime = Uri.encodeComponent(item['startTime']);
  //   final encodedendTime = Uri.encodeComponent(item['endTime']);
  //
  //   NavigatorUtils.push(
  //     context,
  //     '${XDeviceRouter.dataSelectPage}?camId=$_camId'
  //         '&weekId=${item['weekId']}&week=$encodedweek'
  //         '&startTime=$encodedstartTime&endTime=$encodedendTime',
  //   );
  // }

  // 移动侦测时间段项点击事件处理
  void _onDefenseItemTap(dynamic item) {
    final encodedweek = Uri.encodeComponent(item['week']);
    final encodedstartTime = Uri.encodeComponent(item['startTime']);
    final encodedendTime = Uri.encodeComponent(item['endTime']);

    // 调用带返回值的pushResult方法
    NavigatorUtils.pushResult(
      context,
      '${XDeviceRouter.dataSelectPage}?camId=$_camId'
          '&weekId=${item['weekId']}&week=$encodedweek'
          '&startTime=$encodedstartTime&endTime=$encodedendTime',
          (result) {  // 页面返回时触发
        // 无论返回什么结果，都刷新数据
        _fetchDefenseSettingData();
      },
    );
  }

  // 防区设置开关状态变化处理
  Future<void> _onDefenseSwitchChanged(int index, int newValue) async {

    final toUpdate = {
      "weekId": index,
      "weekStatus": newValue,
    };
    final response = await _alarmApi.updateTimeButton(toUpdate);
  }



  // 格式化星期文本显示
  // 格式化星期文本显示
  String _formatWeekText(String weekStr) {
    // 分割并去重
    List<String> weekdays = weekStr.split('、').toSet().toList();

    // 定义所有星期的集合
    const allDaysSet = {'周一', '周二', '周三', '周四', '周五', '周六', '周日'};

    // 判断是否包含所有7天
    bool containsAllDays = weekdays.length == 7 &&
        weekdays.every((day) => allDaysSet.contains(day));

    // 判断是否只包含周末
    bool isWeekend = weekdays.length == 2 &&
        weekdays.contains('周六') &&
        weekdays.contains('周日');
    if (containsAllDays) {
      return "每天";
    } else if (isWeekend) {
      return "周末";
    } else {
      return weekStr;
    }
  }



}